package org.browntooth.app.communicator;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

import org.browntooth.app.bluetooth.BluetoothDeviceConnection;
import org.browntooth.app.bluetooth.messaging.BluetoothMessage;
import org.browntooth.app.bluetooth.messaging.SyncBluetoothMessagingDeviceConnection;

import android.util.Log;

public class BrowntoothCommunication extends Thread {
	private final BluetoothDeviceConnection connection;
	private SyncBluetoothMessagingDeviceConnection messagingConnection;

	public BrowntoothCommunication(BluetoothDeviceConnection connection)
			throws IOException {
		this.connection = connection;
		messagingConnection = new SyncBluetoothMessagingDeviceConnection(
				this.connection);
	}

	@Override
	public void run() {
		try {
			while (true) {
				String request = recieve();
				Log.d("Browntooth", "REQUEST:  [" + request + "]");

				String response = processRequest(request);
				Log.d("Browntooth", "RESPONCE: [" + request + "]");
				send(response);
			}
		} catch (IOException e) {
			Log.e("Browntooth", "Com failed!: " + e.getMessage(), e);
		}
	}

	private String recieve() throws IOException {
		BluetoothMessage message = messagingConnection.waitForMessage();

		try {
			return message.getDataAsUtf8String();
		} catch (UnsupportedEncodingException e) {
			return null;
		}
	}

	private void send(String data) throws IOException {
		try {
			BluetoothMessage message = new BluetoothMessage(data);
			messagingConnection.send(message);
		} catch (UnsupportedEncodingException e) {
			Log.e("Browntooth", "Send failed: " + e.getMessage(), e);
		}
	}

	private String processRequest(String request) {
		return request.toUpperCase() + " | " + request.toLowerCase()
				+ " | MOO!";
	}
}
